import sys
AllClass=["米饭","鱼香肉丝","西红柿炒鸡蛋"]
Root="runs/detect/exp"
BAT="@echo off\npython detect.py --weights foodbest.pt --conf 0.1  --save-txt --source "
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import *
from detect import *
import subprocess as sc
import pymysql
# 运行相应的bat文件







def cmd_test(s):
    # cmd = 'cmd.exe d:/start.bat'
    f=open("runtrain.bat","w")
    f.write(s)
    f.close()
    p = sc.Popen("cmd.exe /c" + "runtrain.bat", stdout=sc.PIPE, stderr=sc.STDOUT)
    curline = p.stdout.readline()
    while (curline != b''):
        curline = p.stdout.readline()
        print(curline)

class picture(QWidget):
    # 初始化对话框
    def __init__(self):
        self.T=1
        super(picture, self).__init__()

        self.resize(800, 600)
        self.setWindowTitle("label显示图片")

        self.label = QLabel(self)
        self.label.setText("   显示图片")
        self.label.resize(400,400)
        self.label.move(0, 100)

        self.label.setStyleSheet("QLabel{background:white;}"
                                 "QLabel{color:rgb(300,300,300,120);font-size:10px;font-weight:bold;font-family:宋体;}"
                                 )
        self.btn = QPushButton(self)
        self.btn.setText("打开图片")
        self.btn.move(10, 30)
        self.btn.clicked.connect(self.openimage)

        self.testEdit=QTextEdit(self)
        self.testEdit.setText("")
        self.testEdit.move(410,100)
        self.testEdit.resize(400,200)
        # 对应的右边的显示信息
        self.testEditplus = QTextEdit(self)
        self.testEditplus.setText("")
        self.testEditplus.move(410, 300)
        self.testEditplus.resize(400, 200)
    def show_text(self,filepath):
        ans=[]
        txt=open(filepath)
        for row in txt:
            col=row.split(" ")
            ans.append(AllClass[int(col[0])])
        return ans

    def openimage(self):
        self.testEdit.clear() # 清空相应的数据集
        self.T+=1
        imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
        jpg = QtGui.QPixmap(imgName).scaled(self.label.width(), self.label.height())
        self.label.setPixmap(jpg)
        cmd_test(BAT+imgName) # 进行检测
        # 获取图片的名称

        ans=self.show_text(Root+str(self.T)+"/labels/"+"1.txt")
        for i in ans:
            self.testEdit.append(i)
        #print(ans[0])  #ans[0]存放识别后菜品名称
        #数据库操作
        db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='demo1', charset='utf8')
        cursor = db.cursor()
        sql = "SELECT * FROM `imagelist` WHERE NAME='"+ans[0]+"'";
        cursor.execute(sql)
        data=cursor.fetchone()
        self.testEditplus.append("热量：")
        self.testEditplus.append(data[1])
        self.testEditplus.append("食物组成：")
        self.testEditplus.append(data[2])
        db.close()


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    my = picture()
    my.show()
    sys.exit(app.exec_())